


package jnpf.fico.controller;

import cn.hutool.core.collection.IterUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jnpf.base.ActionResult;
import jnpf.base.UserInfo;
import jnpf.base.vo.PageListVO;
import jnpf.base.vo.PaginationVO;
import jnpf.exception.DataException;
import jnpf.fico.entity.ZcglCwSzEntity;
import jnpf.fico.entity.ZcglCwSzItemEntity;
import jnpf.fico.model.sz.*;
import jnpf.fico.service.ZcglCwSzItemService;
import jnpf.fico.service.ZcglCwSzService;
import jnpf.util.GeneraterSwapUtil;
import jnpf.util.JsonUtil;
import jnpf.util.RandomUtil;
import jnpf.util.UserProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;


/**
 * 收支详情
 *
 * @版本： V3.2.0
 * @版权： 智果云科技（https://www.jnpfsoft.com）
 * @作者： JNPF开发平台组
 * @日期： 2024-10-25
 */
@Slf4j
@RestController
@Api(tags = "收支详情", value = "example")
@RequestMapping("/api/example/ZcglCwSz")
public class ZcglCwSzController {

    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;


    @Autowired
    private UserProvider userProvider;


    @Autowired
    private ZcglCwSzService zcglCwSzService;

    @Autowired
    private ZcglCwSzItemService zcglCwSzItemService;


    /**
     * 列表
     *
     * @param zcglCwSzPagination
     * @return
     */
    @ApiOperation("获取列表")
    @PostMapping("/getList")
    public ActionResult list(@RequestBody ZcglCwSzPagination zcglCwSzPagination) throws IOException {
        List<ZcglCwSzEntity> list = zcglCwSzService.getList(zcglCwSzPagination);
        //处理id字段转名称，若无需转或者为空可删除

        List<ZcglCwSzListVO> listVO = JsonUtil.getJsonToList(list, ZcglCwSzListVO.class);
        for (ZcglCwSzListVO zcglCwSzVO : listVO) {

            zcglCwSzVO.setTransactionTime_name(zcglCwSzVO.getTransactionTime());

            zcglCwSzVO.setTransactionAmount_name(zcglCwSzVO.getTransactionAmount());

            zcglCwSzVO.setCustomerName_name(zcglCwSzVO.getCustomerName());

            //子表数据转换
            List<ZcglCwSzItemEntity> zcglCwSzItemList = zcglCwSzService.getZcglCwSzItemList(zcglCwSzVO.getId(), zcglCwSzPagination);
            List<ZcglCwSzItemModel> zcglCwSzItemModelList = JsonUtil.getJsonToList(zcglCwSzItemList, ZcglCwSzItemModel.class);
            for (ZcglCwSzItemModel zcglCwSzItemModel : zcglCwSzItemModelList) {
            }
            zcglCwSzVO.setZcglCwSzItemList(zcglCwSzItemModelList);
        }

        PageListVO vo = new PageListVO();
        vo.setList(listVO);
        PaginationVO page = JsonUtil.getJsonToBean(zcglCwSzPagination, PaginationVO.class);
        vo.setPagination(page);
        return ActionResult.success(vo);

    }

    @ApiOperation("获取收支列表")
    @PostMapping("/getListPage")
    public ActionResult getListPage(@RequestBody ZcglCwSzPagination zcglCwSzPagination) throws IOException {
        return ActionResult.success(zcglCwSzService.getListPage(zcglCwSzPagination));
    }

    /**
     * 收款接口
     *
     * @param zcglCwSzForm
     * @return
     */
    @PostMapping
    @Transactional
    @ApiOperation("收款")
    public ActionResult create(@RequestBody @Valid ZcglCwSzForm zcglCwSzForm) throws DataException {
        ActionResult actionResult = zcglCwSzService.receive(zcglCwSzForm);
        return actionResult;
    }


    /**
     * 信息
     *
     * @param id
     * @return
     */
    @ApiOperation("信息")
    @GetMapping("/{id}")
    public ActionResult<ZcglCwSzInfoVO> info(@PathVariable("id") String id) {
        ZcglCwSzEntity entity = zcglCwSzService.getInfo(id);
        ZcglCwSzInfoVO vo = JsonUtil.getJsonToBean(entity, ZcglCwSzInfoVO.class);

        //子表
        List<ZcglCwSzItemEntity> ZcglCwSzItemList = zcglCwSzService.getZcglCwSzItemList(id);
        for (ZcglCwSzItemEntity zcglcwszitemEntity : ZcglCwSzItemList) {
        }
        vo.setZcglCwSzItemList(JsonUtil.getJsonToList(ZcglCwSzItemList, ZcglCwSzItemModel.class));
        //副表
        return ActionResult.success(vo);
    }
    /**
     * 根据应收查收支
     *
     * @param id
     * @return
     */
    @ApiOperation("根据应收查收支(详情页)")
    @GetMapping("/detailByBillId/{id}")
    public ActionResult<List<ZcglCwSzInfoVO>> detailByBillId(@PathVariable("id") String id) {

        List<ZcglCwSzEntity> zcglCwSzEntities = zcglCwSzService.list(new QueryWrapper<ZcglCwSzEntity>().eq("BILL_ID",id));
        List<ZcglCwSzInfoVO> list = new ArrayList<>();
        for (int i = 0; i < zcglCwSzEntities.size(); i++) {


            ZcglCwSzEntity entity = zcglCwSzEntities.get(i);
            ZcglCwSzInfoVO vo = JsonUtil.getJsonToBean(entity, ZcglCwSzInfoVO.class);

            //子表数据转换
            List<ZcglCwSzItemEntity> zcglCwSzItemList = zcglCwSzService.getZcglCwSzItemList(zcglCwSzEntities.get(i).getId());
            List<ZcglCwSzItemModel> zcglCwSzItemModelList = JsonUtil.getJsonToList(zcglCwSzItemList, ZcglCwSzItemModel.class);
            for (ZcglCwSzItemModel zcglCwSzItemModel : zcglCwSzItemModelList) {
            }
            vo.setZcglCwSzItemList(zcglCwSzItemModelList);

            //附表数据转换

            //添加到详情表单对象中
            vo.setTransactionTime(vo.getTransactionTime());

            //交易总额汇总计算
            if(IterUtil.isNotEmpty(zcglCwSzItemModelList)){
                // 计算 transactionAmount 字段的总和
                BigDecimal totalTransactionAmount = zcglCwSzItemModelList.stream()
                        .filter(item -> item.getStatus() != 2) // 过滤掉作废状态
                        .map(ZcglCwSzItemModel::getTransactionAmount) // 获取每个模型的 transactionAmount
                        .filter(amount -> amount != null) // 过滤掉 null
                        .reduce(BigDecimal.ZERO, BigDecimal::add);   // 进行相加
                vo.setTransactionAmountSum(totalTransactionAmount);
            }
            list.add(vo);

        }




        return ActionResult.success(list);
    }

    /**
     * 表单信息(详情页)
     *
     * @param id
     * @return
     */
    @ApiOperation("表单信息(详情页)")
    @GetMapping("/detail/{id}")
    public ActionResult<ZcglCwSzInfoVO> detailInfo(@PathVariable("id") String id) {
        ZcglCwSzEntity entity = zcglCwSzService.getInfo(id);
        ZcglCwSzInfoVO vo = JsonUtil.getJsonToBean(entity, ZcglCwSzInfoVO.class);

        //子表数据转换
        List<ZcglCwSzItemEntity> zcglCwSzItemList = zcglCwSzService.getZcglCwSzItemList(id);
        List<ZcglCwSzItemModel> zcglCwSzItemModelList = JsonUtil.getJsonToList(zcglCwSzItemList, ZcglCwSzItemModel.class);
        for (ZcglCwSzItemModel zcglCwSzItemModel : zcglCwSzItemModelList) {
        }
        vo.setZcglCwSzItemList(zcglCwSzItemModelList);

        //附表数据转换

        //添加到详情表单对象中
        vo.setTransactionTime(vo.getTransactionTime());

        //交易总额汇总计算
        if(IterUtil.isNotEmpty(zcglCwSzItemModelList)){
            // 计算 transactionAmount 字段的总和
            BigDecimal totalTransactionAmount = zcglCwSzItemModelList.stream()
                    .filter(item -> item.getStatus() != 2) // 过滤掉作废状态
                    .map(ZcglCwSzItemModel::getTransactionAmount) // 获取每个模型的 transactionAmount
                    .filter(amount -> amount != null) // 过滤掉 null
                    .reduce(BigDecimal.ZERO, BigDecimal::add);   // 进行相加
            vo.setTransactionAmountSum(totalTransactionAmount);
        }

        return ActionResult.success(vo);
    }

    /**
     * 收支详情作废
     * @param zcglCwSzForm
     * @return
     */
    @PostMapping(value = "nullify")
    public ActionResult nullify(@RequestBody @Valid ZcglCwSzForm zcglCwSzForm){
        ActionResult actionResult = zcglCwSzService.nullify(zcglCwSzForm);
        return actionResult;
    }


    /**
     * 更新
     *
     * @param id
     * @param zcglCwSzForm
     * @return
     */
    @PutMapping("/{id}")
    @Transactional
    @ApiOperation("更新")
    public ActionResult update(@PathVariable("id") String id, @RequestBody @Valid ZcglCwSzForm zcglCwSzForm) throws DataException {
        boolean b = zcglCwSzService.checkForm(zcglCwSzForm, 1);
        if (b) {
            return ActionResult.fail("单行输入不能重复");
        }
        UserInfo userInfo = userProvider.get();
        ZcglCwSzEntity entity = zcglCwSzService.getInfo(id);
        if (entity != null) {
            ZcglCwSzEntity subentity = JsonUtil.getJsonToBean(zcglCwSzForm, ZcglCwSzEntity.class);
            boolean b1 = zcglCwSzService.updateById(subentity);
            if (!b1) {
                return ActionResult.fail("当前表单原数据已被调整，请重新进入该页面编辑并提交数据");
            }

            QueryWrapper<ZcglCwSzItemEntity> ZcglCwSzItemqueryWrapper = new QueryWrapper<>();
            ZcglCwSzItemqueryWrapper.lambda().eq(ZcglCwSzItemEntity::getParentid, entity.getId());
            zcglCwSzItemService.remove(ZcglCwSzItemqueryWrapper);
            if (zcglCwSzForm.getZcglcwszitemList() != null) {
                List<ZcglCwSzItemEntity> ZcglCwSzItemList = JsonUtil.getJsonToList(zcglCwSzForm.getZcglcwszitemList(), ZcglCwSzItemEntity.class);
                for (ZcglCwSzItemEntity entitys : ZcglCwSzItemList) {


                    entitys.setId(RandomUtil.uuId());
                    entitys.setParentid(entity.getId());
                    zcglCwSzItemService.save(entitys);
                }
            }
            return ActionResult.success("更新成功");
        } else {
            return ActionResult.fail("更新失败，数据不存在");
        }
    }


    /**
     * 删除
     *
     * @param id
     * @return
     */
    @ApiOperation("删除")
    @DeleteMapping("/{id}")
    @Transactional
    public ActionResult delete(@PathVariable("id") String id) {
        ZcglCwSzEntity entity = zcglCwSzService.getInfo(id);
        if (entity != null) {
            zcglCwSzService.delete(entity);
            QueryWrapper<ZcglCwSzItemEntity> queryWrapperZcglCwSzItem = new QueryWrapper<>();
            queryWrapperZcglCwSzItem.lambda().eq(ZcglCwSzItemEntity::getParentid, entity.getId());

            zcglCwSzItemService.remove(queryWrapperZcglCwSzItem);

        }
        return ActionResult.success("删除成功");
    }


    @ApiOperation("获取收支金额汇总")
    @GetMapping("/getSumMoney")
    public ActionResult getSumMoney(){
        ZcglCwSzSumMoneyDTO zcglCwSzSumMoneyDTO = zcglCwSzService.getSumMoney();
        return ActionResult.success("获取成功",zcglCwSzSumMoneyDTO);
    }

    @ApiOperation("获取退款金额汇总")
    @GetMapping("/getSumTkMoney")
    public ActionResult getSumTkMoney(){
        ZcglCwRefundSumMoneyDTO zcglCwSzServiceSumTkMoney = zcglCwSzService.getSumTkMoney();
        return ActionResult.success("获取成功",zcglCwSzServiceSumTkMoney);
    }


}
